package br.ufrn.cerescaico.sepe.dao;

import br.ufrn.cerescaico.sepe.Sepe;
import br.ufrn.cerescaico.sepe.beans.Participante;
import br.ufrn.cerescaico.sepe.dao.util.DataAccessLayerException;
import br.ufrn.cerescaico.sepe.dao.util.HibernateFactory;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 * @author Taciano Morais Silva
 * @version 23/01/2009, 12h11m
 * @since 15/10/2008, 12h00m
 */
public class ParticipanteDao extends AbstractDao<Participante> implements Dao<Participante> {

    public ParticipanteDao(Sepe sepe) throws DataAccessLayerException {
        super(sepe);
    }

    /**
     *
     * @throws br.cesed.lti.cesuweb.dao.util.DataAccessLayerException
     */
    public ParticipanteDao() throws DataAccessLayerException {
        super();
    }

    /**
     *
     * @param username
     * @param password
     * @return
     * @throws br.cesed.lti.cesuweb.dao.util.DataAccessLayerException
     */
    @SuppressWarnings("unchecked")
    public Participante autenticar(String username, String password) throws DataAccessLayerException {
        Participante participante = null;
        try {
            startOperation();
            Criteria criteria = session.createCriteria(Participante.class);
            if (username != null && !username.equals("") && password != null && !password.equals("")) {
                criteria.add(Restrictions.eq("email", username));
                criteria.add(Restrictions.eq("senha", password));
            }
            List<Participante> participantes = criteria.list();
            if (participantes.size() > 1) {
                throw new DataAccessLayerException("erro.participante.dao.participante.duplicado");
            } else if (!participantes.isEmpty()) {
                participante = participantes.get(PRIMEIRO_REGISTRO);
            }
            tx.commit();
        } catch (HibernateException e) {
            handleException(e);
        } finally {
            HibernateFactory.close(session);
        }
        return participante;
    }

    /**
     * Verifica se o login passado como parâmetro já existe.
     * @param username O login a verificar.
     * @return True se o login existir.
     * @throws br.cesed.lti.cesuweb.dao.util.DataAccessLayerException Caso
     * ocorra erro no acesso ao banco de dados
     */
    public Participante verificarEmailExistente(Participante participante) throws DataAccessLayerException {
        Participante participanteBD = null;
        try {
            startOperation();
            Criteria criteria = session.createCriteria(Participante.class);

            if (participante != null && participante.getEmail() != null && !participante.getEmail().equals("")) {
                criteria.add(Restrictions.eq("email", participante.getEmail()));
                participanteBD = (Participante) criteria.uniqueResult();
            }

            tx.commit();
        } catch (HibernateException e) {
            handleException(e);
        } finally {
            HibernateFactory.close(session);
        }
        return participanteBD;
    }

    /**
     * Insert a new Event into the database.
     * @param event
     */
    @Override
    public void create(Participante participante) throws DataAccessLayerException {
        super.saveOrUpdate(participante);
    }

    /**
     * Delete a detached Event from the database.
     * @param event
     */
    @Override
    public void delete(Participante participante) throws DataAccessLayerException {
        super.delete(participante);
    }

    /**
     * Delete a detached Event from the database.
     * @param id
     */
    @Override
    public void delete(Integer id) throws DataAccessLayerException {
        super.delete(Participante.class, id);
    }

    /**
     * Find an Event by its primary key.
     * @param id
     * @return
     */
    @Override
    public Participante find(Integer id) throws DataAccessLayerException {
        return (Participante) super.find(Participante.class, id);
    }

    public Participante find(String email) throws DataAccessLayerException {
        Participante participante = null;
        try {
            startOperation();
            Criteria criteria = session.createCriteria(Participante.class);
            if (email != null && !email.equals("")) {
                criteria.add(Restrictions.ilike("email", email.trim()));
            }
            participante = (Participante) criteria.uniqueResult();
            tx.commit();
        } catch (HibernateException e) {
            handleException(e);
        } finally {
            HibernateFactory.close(session);
        }
        return participante;
    }

    /**
     *
     * @param login
     * @param nome
     * @param perfil
     * @return
     * @throws 
     */
    public List<Participante> pesquisar(String email, String nome) throws DataAccessLayerException {
        List<Participante> participantes = null;
        try {
            startOperation();
            Criteria criteria = session.createCriteria(Participante.class);
            if (email != null && !email.equals("")) {
                criteria.add(Restrictions.ilike("email", "%" + email + "%"));
            }
            if (nome != null && !nome.equals("")) {
                criteria.add(Restrictions.ilike("nome", "%" + nome + "%"));
            }
            participantes = (List<Participante>) criteria.list();
            tx.commit();
        } catch (HibernateException e) {
            handleException(e);
        } finally {
            HibernateFactory.close(session);
        }
        return participantes;
    }

    public List<Participante> findAllOrderByEmail() throws DataAccessLayerException {
        List<Participante> participantes = null;
        try {
            startOperation();
            Criteria criteria = session.createCriteria(Participante.class);
            criteria.addOrder(Order.asc("email"));
            participantes = (List<Participante>) criteria.list();
            tx.commit();
        } catch (HibernateException e) {
            handleException(e);
        } finally {
            HibernateFactory.close(session);
        }
        return participantes;
    }

    /**
     * Updates the state of a detached Event.
     *
     * @param event
     */
    @Override
    public void update(Participante participante) throws DataAccessLayerException {
        super.saveOrUpdate(participante);
    }

    /**
     * Finds all Events in the database.
     * @return
     */
    @Override
    public List<Participante> findAll() throws DataAccessLayerException {
        return super.findAll(Participante.class);
    }

    /**
     *
     * @param id
     * @throws br.cesed.lti.cesuweb.dao.util.DataAccessLayerException
     */
    public void deleteUser(Integer id) throws DataAccessLayerException {
        try {
            startOperation();
            Query q = session.createQuery("delete from Participante where id = " + id);
            q.executeUpdate();
            tx.commit();
        } catch (HibernateException e) {
            handleException(e);
        } finally {
            HibernateFactory.close(session);
        }
    }
}
